package db_main

import (
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"
)

// 用户私聊相关统计
func InsertStatPrivateChat(userPrivateChatLog *models_main.UserPrivateChatLog) error {
	userPrivateChatLog.Date = time.Now()
	userPrivateChatLog.CreateTime = time.Now()

	officialUid1 := global.Config.GetInt("official.anchor1.uid")
	officialUid2 := global.Config.GetInt("official.anchor2.uid")
	var existUserCount int64
	var userCount int
	var chatCount int
	if officialUid1 != userPrivateChatLog.SenderUid && officialUid2 != userPrivateChatLog.SenderUid {
		err := global.GetX().Model(&models_main.UserPrivateChatLog{}).Where("source_key=? and date=? and sender_uid = ?",
			userPrivateChatLog.SourceKey,
			userPrivateChatLog.Date.Format("2006-01-02"),
			userPrivateChatLog.SenderUid,
		).Count(&existUserCount).Error
		if err != nil {
			return err
		}

		if existUserCount == 0 {
			userCount = userCount + 1
		}
	}

	err := mysql.GetXTable(&models_main.UserPrivateChatLog{}).Create(userPrivateChatLog).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	chatCount = chatCount + 1
	tx := global.GetX().Begin()
	var exist int64

	err = tx.Model(&models_main.StatPrivateChatLog{}).Where("source_key=? and date=?", userPrivateChatLog.SourceKey, userPrivateChatLog.Date.Format("2006-01-02")).
		Count(&exist).
		Update("chat_count", gorm.Expr("chat_count+1")).
		Update("user_count", gorm.Expr(fmt.Sprintf("user_count+%d", userCount))).
		Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("StatUserRegisterChannelHandler Error: ", err)
	}

	if exist == 0 {
		r := &models_main.StatPrivateChatLog{
			SourceKey:  userPrivateChatLog.SourceKey,
			Date:       userPrivateChatLog.Date,
			UserCount:  userCount,
			ChatCount:  chatCount,
			CreateTime: userPrivateChatLog.CreateTime,
		}

		err = tx.Model(&models_main.StatPrivateChatLog{}).Create(&r).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	tx.Commit()

	return nil
}
